package com.kingyun.gpsinspection.purificationservice.services.tdm.innerservice.impl;

import com.alibaba.fastjson.JSON;
import com.cqhilink.api.common.utils.UniqueUtil;
import com.kingyun.gpsinspection.purificationservice.common.utils.FileTypeUtil;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.tdm.DisposeMeasureMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.tdm.TdmFileMapper;
import com.kingyun.gpsinspection.purificationservice.dao.mapper.tdm.TdmProblemMapper;
import com.kingyun.gpsinspection.purificationservice.facade.model.File;
import com.kingyun.gpsinspection.purificationservice.facade.model.jsm.EmployeeVo;
import com.kingyun.gpsinspection.purificationservice.facade.model.tdm.DisposeMeasure;
import com.kingyun.gpsinspection.purificationservice.facade.model.tdm.DisposeMeasureVo;
import com.kingyun.gpsinspection.purificationservice.facade.model.tdm.Problem;
import com.kingyun.gpsinspection.purificationservice.facade.model.tdm.ProblemVo;
import com.kingyun.gpsinspection.purificationservice.facade.service.tdm.DisposeMeasureService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 处置措施业务层
 * Created by sugongche on 2016/11/22.
 */
public class DisposeMeasureImpl implements DisposeMeasureService {
    @Autowired
    private DisposeMeasureMapper disposeMeasureMapper;
    @Autowired
    private TdmProblemMapper tdmProblemMapper;
    @Autowired
    private TdmFileMapper tdmFileMapper;

    /**
     * 获取页面列表对应的数据
     *
     * @param employeeVo
     * @param problemVo
     * @return
     * @throws Exception
     */
    @Override
    public Map<String, Object> listMap(EmployeeVo employeeVo, ProblemVo problemVo) throws Exception {
        Map<String, Object> map = new HashMap<>();

        problemVo.setLimit(problemVo.getLimit() == null ? 10 : problemVo.getLimit());
        problemVo.setOffset(problemVo.getOffset() == null ? 0 : problemVo.getOffset());
        //设置过滤条件
        problemVo.setFilterEmployeeId(employeeVo.getEmployeeId());
        problemVo.setFilterOrgId(employeeVo.getOrgId());
        //查询
        int total = disposeMeasureMapper.queryCount(problemVo);
        List<ProblemVo> list = disposeMeasureMapper.queryList(problemVo);

        // 关联查询WWP_DISPOSE_MEASURE表如果没有数据，则disposeMeasureVo属性为null，
        // 则返回到前台的json中则没有disposeMeasureVo字段，因此无法用bootstrap-table展示,必须作如下处理
        for (ProblemVo problem : list) {
            if (problem.getDisposeMeasureVo() == null) {
                //返回到前台的json中显示disposeMeasureVo:{}
                problem.setDisposeMeasureVo(new DisposeMeasureVo());
            }
        }

        map.put("total", total);
        map.put("rows", list);
        return map;
    }

    /**
     * 保存
     * 注意：注解开启事务，不能抛异常
     *
     * @param employeeVo
     * @param disposeMeasure
     * @param uploadFiles
     * @param deletedFiles   @return
     * @throws Exception
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int save(EmployeeVo employeeVo, DisposeMeasure disposeMeasure, String uploadFiles, String deletedFiles) {
        if (disposeMeasure == null) {
            return 0;
        }

        //更新问题状态
        Problem problem = new Problem();
        problem.setProblemId(disposeMeasure.getProblemId());
        problem.setStatus((short) 5);
        tdmProblemMapper.updateByPrimaryKeySelective(problem);

        disposeMeasure.setMeasureId(UniqueUtil.uuid());
        disposeMeasure.setCreateUserId(employeeVo.getEmployeeId());
        disposeMeasure.setModifyUserId(employeeVo.getEmployeeId());
        disposeMeasure.setIsDelete((short) 0);
        //1问题和处置措施模块提出的处置措施；2分析处理提出的处置措施
        disposeMeasure.setSourceValue((short) 1);
        int a = disposeMeasureMapper.insertNew(disposeMeasure);

        if (StringUtils.isNotBlank(uploadFiles)) {
            //强制转换成集合
            List<File> listFiles = JSON.parseArray(uploadFiles, File.class);

            //重新设置附件属性
            for (int i = 0; i < listFiles.size(); i++) {
                File _file = listFiles.get(i);
                //设置主键
                _file.setFileId(UniqueUtil.uuid());
                //设置业务数据id
                _file.setBusinessId(disposeMeasure.getMeasureId());
                _file.setFileType((short) FileTypeUtil.getFileTypeByFileName(_file.getFileName()));
            }

            //必须判断非空
            if (listFiles != null && listFiles.size() > 0) {
                a += tdmFileMapper.insertByList(listFiles);
            }
        }

        //需要删除的附件信息
        if (StringUtils.isNotBlank(deletedFiles)) {
            //强制转换成集合
            List<File> listFiles = JSON.parseArray(deletedFiles, File.class);
            if (listFiles != null && listFiles.size() > 0) {
                int len = listFiles.size();
                for (int i = 0; i < len; i++) {
                    File _file = listFiles.get(i);
                    a += tdmFileMapper.deleteByPrimaryKey(_file.getFileId());
                }
            }
        }


        /*List<File> newList=new ArrayList<>();
        if(uploadFiles !=null && uploadFiles.length>0 && deletedFiles !=null && deletedFiles.length>0){
            for(int i = 0; i< uploadFiles.length; i++){
                File newFile=new File();

                newFile.setFileId(UniqueUtil.uuid());
                newFile.setBusinessId(disposeMeasure.getMeasureId());
                newFile.setFileName(uploadFiles[i]);
                newFile.setFileType((short)FileTypeUtilEnum.getFileTypeByFileName(uploadFiles[i]));
                newFile.setFileHbasePath(deletedFiles[i]);

                newList.add(newFile);
            }
        }
        //必须判断非空
        if(newList!=null && newList.size()>0){
            a=tdmFileMapper.insertByList(newList);
        }*/

        return a;
    }

    /**
     * 更新处置建议，并更新附件表
     *
     * @param employeeVo
     * @param disposeMeasure
     * @param uploadFiles
     * @param deletedFiles
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int update(EmployeeVo employeeVo, DisposeMeasure disposeMeasure, String uploadFiles, String deletedFiles) {
        if (disposeMeasure == null) {
            return 0;
        }

        disposeMeasure.setModifyUserId(employeeVo.getEmployeeId());
        int a = disposeMeasureMapper.updateByPrimaryKeyNew(disposeMeasure);

        //更新附件信息
        if (StringUtils.isNotBlank(uploadFiles)) {
            //强制转换成集合
            List<File> listFiles = JSON.parseArray(uploadFiles, File.class);
            if (listFiles != null && listFiles.size() > 0) {
                //重新设置附件属性
                String pId = disposeMeasure.getMeasureId();
                int len = listFiles.size();
                for (int i = 0; i < len; i++) {
                    File _file = listFiles.get(i);
                    //设置主键
                    _file.setFileId(UniqueUtil.uuid());
                    //设置业务数据id
                    _file.setBusinessId(pId);
                    _file.setFileType((short) FileTypeUtil.getFileTypeByFileName(_file.getFileName()));
                }
                a += tdmFileMapper.insertByList(listFiles);
            }
        }

        //需要删除的附件信息
        if (StringUtils.isNotBlank(deletedFiles)) {
            //强制转换成集合
            List<File> listFiles = JSON.parseArray(deletedFiles, File.class);
            if (listFiles != null && listFiles.size() > 0) {
                int len = listFiles.size();
                for (int i = 0; i < len; i++) {
                    File _file = listFiles.get(i);
                    a += tdmFileMapper.deleteByPrimaryKey(_file.getFileId());
                }
            }
        }

        /*int b=tdmFileMapper.delByBusinessId(disposeMeasure.getMeasureId());
        List<File> newList=new ArrayList<>();
        if(uploadFiles !=null && uploadFiles.length>0 && deletedFiles !=null && deletedFiles.length>0){
            for(int i = 0; i< uploadFiles.length; i++){
                File newFile=new File();

                newFile.setFileId(UniqueUtil.uuid());
                newFile.setBusinessId(disposeMeasure.getMeasureId());
                newFile.setFileName(uploadFiles[i]);
                newFile.setFileType((short)FileTypeUtilEnum.getFileTypeByFileName(uploadFiles[i]));
                newFile.setFileHbasePath(deletedFiles[i]);

                newList.add(newFile);
            }
        }
        //必须判断非空
        if(newList!=null && newList.size()>0){
            a=tdmFileMapper.insertByList(newList);
        }*/

        return a;
    }

    /**
     * 根据主键查询上报问题
     *
     * @param measureId
     * @return
     */
    @Override
    public DisposeMeasureVo queryVoById(String measureId) throws Exception {
        if (StringUtils.isBlank(measureId)) {
            return null;
        }

        DisposeMeasureVo disposeMeasureVo = disposeMeasureMapper.selectByPrimaryKeyNew(measureId);

        return disposeMeasureVo;
    }

    /**
     * 根据问题ID查询处置
     *
     * @param problemId
     * @return
     * @throws Exception
     */
    @Override
    public DisposeMeasureVo queryVoByProblemId(String problemId) throws Exception {
        List<DisposeMeasureVo> list = disposeMeasureMapper.selectByProblemId(problemId);

        if (list != null && list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }

    /**
     * 删除:软删除
     *
     * @param list
     * @return
     */
    @Override
    public int delByIds(List<String> list) throws Exception {
        if (list == null || (list != null && list.size() == 0)) {
            return 0;
        }

        int i = disposeMeasureMapper.updateStateByIds(list);

        return i;
    }

    /**
     * 根据主键查询
     *
     * @param id
     * @return
     */
    @Override
    public DisposeMeasure queryByPrimaryKey(String id) {
        DisposeMeasure disposeMeasure = disposeMeasureMapper.selectByPrimaryKey(id);

        return disposeMeasure;
    }
}
